const express = require('express')
const multer = require('multer')
const moment = require('moment')
const fs = require('fs')
const app = express()
const config = global.config

// 支持跨域
app.all('*', function (req, res, next) {
  let path = req.path.toLowerCase()
  let lpath = path
  let method = req.method.toLowerCase()

  // 允许的请求头
  let headers = config.headers || {}
  for (let key in headers) {
    res.header(key, headers[key])
  }

  // 允许跨域访问
  if (config.isCrossOrigin) {
    res.setHeader('Access-Control-Allow-Origin', '*')
  }

  // 动态origin
  if (String(config.isDynamicOrigin) === '1' || String(config.isDynamicOrigin) === 'true') {
    res.setHeader("Access-Control-Allow-Origin", req.headers.origin || '*')
  }

  if (/options|head/i.test(method)) {
    res.status(204).send('OK')
    res.end()
  }
  // 通用请求或已经请求
  else {
    next()
  }
})

// 设置中间件和路由
app.use(express.json()) // 解析JSON数据
app.use(express.urlencoded({ extended: true })) // 解析URL编码数据  

// 使用multer中间件处理文件上传
const upload = multer({ dest: 'temp/' })

// 创建路由以处理POST请求
app.post('/upload', upload.single('file'), (req, res) => {  
  // 获取上传的文件
  const file = req.file;  

  // 获取文件的扩展名  
  const ext = file.originalname.split('.').pop();

  // 生成新的文件名，格式为年月日_时分秒.txt  
  const newName = moment().format('YYYYMMDD_HHmmss') + '.' + ext;  

  // 将文件从临时目录移动到当前目录，并重命名文件
  fs.rename(file.path, config.uploadPath + '/' + newName, (err) => {  
    if (err) {
      console.error(err)
      return res.status(500).send() 
    }
    console.log(`File ${file.originalname} has been uploaded and saved as ${newName}`);  
    res.send(`File ${file.originalname} has been uploaded and saved as ${newName}`);  
  })
})

// 静态目录
app.use('/', express.static(config.accessRootDir))

// 启动服务器并监听端口
app.listen(config.PORT, () => {
  console.log('服务端->http://127.0.0.1:' + config.PORT)
})